package com.app.execptions;

import com.app.enums.ResultCodeEnum;
import com.app.utils.Result;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobeException {


    @ExceptionHandler(Throwable.class)
    public Result<Object> bindException(Throwable exception) {
        exception.printStackTrace();
        return Result.fail().setMsg(exception.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> bindException(Exception exception) {
        exception.printStackTrace();
        return Result.fail().setMsg(exception.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public Result<Object> bindException(RuntimeException exception) {
        exception.printStackTrace();
        return Result.fail().setMsg(exception.getMessage());
    }


    @ExceptionHandler(MyRuntimeException.class)
    public Result<Object> bindException(MyRuntimeException exception) {
        exception.printStackTrace();
        return Result.fail().setMsg(exception.getMsg());
    }

    @ExceptionHandler(BindException.class)
    public Result<Object> bindException(BindException exception) {
        exception.printStackTrace();
        String msg = exception.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        return Result.fail().setMsg(msg);
    }


    @ExceptionHandler(UnauthorizedException.class)
    public Result<Object> bindException(UnauthorizedException exception) {
        exception.printStackTrace();
        return Result.fail().setMsg("暂无权限").setCode(ResultCodeEnum.TOKEN_ERROR.getCode());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<Object> bindException(HttpRequestMethodNotSupportedException exception) {
        exception.printStackTrace();
        return Result.fail().setMsg("登录过期").setCode(ResultCodeEnum.TOKEN_ERROR.getCode());
    }


}
